<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2023/4/20
 * Time: 23:36
 */

namespace app\backstage\controller;

use app\backstage\server\UploadServer;
use app\common\model\PaymentNumber;
use think\Controller;
use think\Db;
use think\facade\Env;
use think\facade\Request;

/**
 * 工具类
 * Class Tool
 * @package app\backstage\controller
 */
class Tool extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => ['uploadPic','UploadFile']],
    ];

    public function UploadFile()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $dirName = input('dirName', 'novel');
        $file = request()->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->validate([])->move('./uploads');
        if ($info) {
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            $filepath = Env::get('root_path') . "public/uploads/" . $info->getSaveName();

            $server = new UploadServer();
            $ossPath = $server->putFileToOss($info->getFilename(), $filepath, $dirName);
            $this->success('', null, ['picUrl' => config('img_domain') . $ossPath, 'filePath' => $ossPath]);
        } else {
            $this->error($file->getError());
        }
    }

    public function uploadPic()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $dirName = input('dirName', 'novel');
        $file = request()->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->validate(['ext' => 'jpg,jpeg,png,gif'])->move('./uploads');
        if ($info) {
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            $filepath = Env::get('root_path') . "public/uploads/" . $info->getSaveName();

            $server = new UploadServer();
            $ossPath = $server->putFileToOss($info->getFilename(), $filepath, $dirName);
            $this->success('', null, ['picUrl' => config('img_domain') . $ossPath, 'filePath' => $ossPath]);
        } else {
            $this->error($file->getError());
        }
    }

    /**
     * 待开发页面...
     */
    public function temp()
    {
        return $this->fetch('/404');
    }

    /**
     * 支付号列表
     * @return mixed|\think\response\Json
     */
    public function paymentNumber()
    {
        if (request()->isAjax()) {
            $name = input('name');
            $pay_mode = input('pay_mode');
            $payment_type = input('payment_type');
            $page = input('page', 1);
            $limit = input('limit', 20);
            $where = [];
            if ($name != '') {
                $where[] = ['name', 'like', "%{$name}%"];
            }
            if ($pay_mode != '') {
                $where[] = ['pay_mode', '=', $pay_mode];
            }
            if ($payment_type != '') {
                $where[] = ['payment_type', '=', $payment_type];
            }
            $list = PaymentNumber::where($where)->page($page, $limit)->order("id desc")->select();
            $count = PaymentNumber::where($where)->count();
            return sucJson($list, $count);
        }
        return $this->fetch();
    }

    /**
     * 表单详情
     * @return mixed
     */
    public function paymentNumberForm()
    {
        $pay_mode = input('pay_mode');
        $payment_type = input('payment_type');
        $id = input('id');
        $info = null;
        if ($id) {
            $info = $pn = PaymentNumber::get($id);
            if (!$pn) {
                $this->error('支付号不存在');
            }
            $pay_mode = $pn->pay_mode;
            $payment_type = $pn->payment_type;
        }
        $this->assign('info', $info);
        if ($payment_type == 1) {
            if ($pay_mode == 1) {
                //微信原生
                return $this->fetch('tool/payment/native_wechat');
            } else {
                //支付宝原生
                return $this->fetch('tool/payment/native_ali');
            }
        } elseif ($payment_type == 2) {
            if ($pay_mode == 1) {
                //米花微信
                return $this->fetch('tool/payment/mihua_wechat');
            } else {
                //米花支付宝
                return $this->fetch('tool/payment/mihua_ali');
            }
        } elseif ($payment_type == 3) {
            if ($pay_mode == 1) {
                //富友微信
                return $this->fetch('tool/payment/fuyou_wechat');
            } else {
                //富友支付宝
                return $this->fetch('tool/payment/fuyou_ali');
            }
        } else {
            $this->error('类型异常');
        }
        return $this->fetch();
    }

    /**
     * 设置支付号
     */
    public function setPaymentNumber()
    {
        $pay_mode = input('pay_mode');
        $payment_type = input('payment_type');
        $str = '';
        if ($payment_type == 1) {
            if ($pay_mode == 1) {
                //微信原生
                $str = "native_wechat";
            } else {
                //支付宝原生
                $str = "native_ali";
            }
        } elseif ($payment_type == 2) {
            if ($pay_mode == 1) {
                //米花微信
                $str = "mihua_wechat";
            } else {
                //米花支付宝
                $str = "mihua_ali";
            }
        } elseif ($payment_type == 3) {
            if ($pay_mode == 1) {
                //富友微信
                $str = "fuyou_wechat";
            } else {
                //富友支付宝
                $str = "fuyou_ali";
            }
        }
        if (!$str) {
            $this->error('类型异常');
        }
        $params = $this->request->post();
        $result = $this->validate($params, 'app\backstage\validate\ToolValidate.' . $str);
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        if ($id) {
            $pn = PaymentNumber::get($id);
            if (!$pn) {
                $this->error('支付号不存在');
            }
            if ($pn->pay_mode != $pay_mode || $pn->payment_type != $payment_type) {
                $this->error('参数异常');
            }
        } else {
            $pn = new PaymentNumber();
        }
        $pn->allowField(true)->save($_POST);
        $this->success();
    }

    /**
     * 设置支付号默认状态
     */
    public function setDefaultPayment()
    {
        $params = $this->request->post();
        $result = $this->validate($params, 'app\backstage\validate\ToolValidate.setDefaultPayment');
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        $value = input('value');
        $pn = PaymentNumber::get($id);
        if (!$pn) {
            $this->error('支付号不存在');
        }
        if ($value == 1) {
            PaymentNumber::where("pay_mode", $pn->pay_mode)->setField("is_default", 0);
        }
        PaymentNumber::where("id", $pn->id)->setField("is_default", $value);
        $this->success();
    }

    /**
     * 报警开关设置
     * @return void
     */
    public function baojingSwitch()
    {
        $params = $this->request->post();
        $result = $this->validate($params, 'app\backstage\validate\ToolValidate.setDefaultPayment');
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        $value = input('value');
        $pn = PaymentNumber::get($id);
        if (!$pn) {
            $this->error('支付号不存在');
        }
        PaymentNumber::where("id", $pn->id)->setField("baojing_switch", $value);
        $this->success();
    }

    /**
     * 报警时间项设置
     * @return void
     */
    public function baojing()
    {
        $params = $this->request->post();
        $result = $this->validate($params, 'app\backstage\validate\ToolValidate.baojing');
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        $value = input('baojing_minute');
        $pn = PaymentNumber::get($id);
        if (!$pn) {
            $this->error('支付号不存在');
        }
        PaymentNumber::where("id", $pn->id)->setField("baojing_minute", $value);
        $this->success();
    }

    /**
     * 报警对象列表
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function paymentAlarm()
    {
        if (request()->isAjax()) {
            $page = input('page', 1);
            $limit = input('limit', 10);
            $list = Db::table('quick_payment_alarm')->page($page, $limit)->order('id desc')->select();
            $count = Db::table("quick_payment_alarm")->count();
            return sucJson($list, $count);
        }
        return $this->fetch();
    }

    /**
     * 删除报警对象
     * @return void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delAlarm()
    {
        $id = input('id', 0);
        if (!$id) {
            $this->error('违规操作');
        }
        Db::table('quick_payment_alarm')->where('id', $id)->delete();
        $this->success();
    }

    /**
     * 新增报警对象
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addAlarm()
    {
        if (request()->isAjax()) {
            $params = $this->request->post();
            $result = $this->validate($params, 'app\backstage\validate\ToolValidate.addAlarm');
            if (true !== $result) {
                $this->error($result);
            }
            $phone = input('phone');
            $name = input('name');
            $alarm = Db::table('quick_payment_alarm')->where('phone', $phone)->find();
            if ($alarm) {
                $this->error('手机号已存在');
            }
            Db::table('quick_payment_alarm')->insert(['name' => $name, 'phone' => $phone]);
            return sucJson();
        }
        return $this->fetch();
    }

    /*书籍充值金额折扣*/
    public function book_discount_money()
    {
        if (request()->isAjax()) {
            $params = Request::post('','','strip_tags,trim');
            $record = Db::table("cps_setting")->where('type','book_discount_money')->field('id')->findOrEmpty();

            if($record)
            {
                Db::table("cps_setting")->where('type','book_discount_money')->update(['data'=>$params['book_discount_money']]);
            }else{
                Db::table("cps_setting")->insert(['data'=>$params['book_discount_money'],'type'=>'book_discount_money']);
            }

            $book_discount_money_list = [];

            if($params['book_discount_money_nid']){
                foreach ($params['book_discount_money_nid'] as $k=>$v)
                {
                    if(strlen($v) >= 1)
                    {
                        $book_discount_money_list[] = [
                            'nid' => $v, 'rate'=> $params['book_discount_money_rate'][$k]
                        ];
                    }

                }
            }

            $recordlist = Db::table("cps_setting")->where('type','book_discount_money_list')->field('id')->findOrEmpty();
            if($recordlist)
            {
                Db::table("cps_setting")->where('type','book_discount_money_list')->update(['data'=>json_encode($book_discount_money_list)]);
            }else{
                Db::table("cps_setting")->insert(['data'=>json_encode($book_discount_money_list),'type'=>'book_discount_money_list']);
            }

            return json(['code'=>1,'msg'=>'操作成功']);
        }

        $record = Db::table("cps_setting")->where('type','book_discount_money')->field('data')->findOrEmpty();

        $book_discount_money = $record ? $record['data'] : '';

        $recordlist = Db::table("cps_setting")->where('type','book_discount_money_list')->field('data')->findOrEmpty();
        $book_discount_money_list = $recordlist ? json_decode($recordlist['data'],true) : [];

        $this->assign('book_discount_money_list', $book_discount_money_list);
        $this->assign('book_discount_money', $book_discount_money);
        return $this->fetch();
    }


}